/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.source.linkedin;

import com.source.model.Certificacion;
import com.source.openoo.OOoInputStream;
import com.source.openoo.OOoOutputStream;
import com.source.openoo.OOoStreamConverter;
import com.sun.star.uno.XComponentContext;
import java.io.Serializable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.samples.odtandfreemarker.model.Educacion;
import fr.opensagres.xdocreport.samples.odtandfreemarker.model.Laboral;
import fr.opensagres.xdocreport.samples.odtandfreemarker.model.ProjectImage;
import fr.opensagres.xdocreport.samples.odtandfreemarker.model.User;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import ooo.connector.BootstrapSocketConnector;

/**
 * 
 * @author magzupao
 */
public class GeneraDocumento implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String nombreDocumento;

    public String getNombreDocumento() {
        return nombreDocumento;
    }

    public void setNombreDocumento(String nombreDocumento) {
        this.nombreDocumento = nombreDocumento;
    }

    public GeneraDocumento() {
    }

    public void documento(StringBuilder cadena, Map<String, String> mMap) {

        System.out.println("DATOS = " + cadena);
        ProcesaXML procesaXML = new ProcesaXML();
        try {

            String oooExecutableFolder = mMap.get("pathOoo");
            XComponentContext xComponentContext = BootstrapSocketConnector.bootstrap(oooExecutableFolder);
            OOoStreamConverter converter = new OOoStreamConverter(xComponentContext);

            procesaXML.procesa(cadena.toString());
            InputStream in = GeneraDocumento.class.getResourceAsStream(mMap.get("plantillaDocumento"));
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Freemarker);

            FieldsMetadata metadata = report.createFieldsMetadata();
            metadata.addFieldAsImage("project.logoFile");
            ProjectImage project = new ProjectImage();
            project.setUrlFoto(procesaXML.getMapDatos().get("foto"));

            // Create context Java model
            IContext context = report.createContext();
            context.put("project", project);

            User user = new User();
            user.setNombre(procesaXML.getMapDatos().get("first_name"));
            user.setApellido(procesaXML.getMapDatos().get("last_name"));
            user.setCategoria(procesaXML.getMapDatos().get("headline"));
            user.setSector(procesaXML.getMapDatos().get("industry"));
            user.setTelefono(mMap.get("telefono"));
            user.setCorreo(mMap.get("mail"));

            context.put("user", user);

            List<Laboral> laborals = new ArrayList<Laboral>();

            for (int i = 0; procesaXML.getListaExperiencia().size() > i; i++) {
                Laboral laboral = new Laboral();
                Map mapa = (Map) procesaXML.getListaExperiencia().get(i);
                laboral.setCargo((String) mapa.get(0));
                laboral.setEmpresa((String) mapa.get(1));
                laboral.setPeriodo((String) mapa.get(2));
                laboral.setFunciones((String) mapa.get(3));
                laborals.add(laboral);
            }
            context.put("laborals", laborals);

            List<Educacion> educacions = new ArrayList<Educacion>();

            for (int i = 0; procesaXML.getListaEducacion().size() > i; i++) {
                Educacion educacion = new Educacion();
                Map mapa = (Map) procesaXML.getListaEducacion().get(i);
                educacion.setIntsuni((String) mapa.get(0));
                educacion.setTitulo((String) mapa.get(1));
                educacion.setEstudio((String) mapa.get(2));
                educacion.setEtapa((String) mapa.get(3));
                educacions.add(educacion);
            }
            context.put("educacions", educacions);

            List<Certificacion> certificacions = new ArrayList<Certificacion>();

            if (procesaXML.getListaCertificacion().size() > 0) {
                System.out.println("existe certificados");
                for (int j = 0; procesaXML.getListaCertificacion().size() > j; j++) {
                    Certificacion certificacion = new Certificacion();
                    Map mapa = (Map) procesaXML.getListaCertificacion().get(j);
                    certificacion.setCertifi((String) mapa.get(j));
                    certificacions.add(certificacion);
                }
            } else {
                System.out.println("no existe certificados");
                Certificacion certificacion = new Certificacion();
                certificacion.setCertifi("");
                certificacions.add(certificacion);
            }
            context.put("certificacions", certificacions);

            // 4) Generate report by merging Java model with the Docx
            String rutaDocWord = mMap.get("pathFisico") + "CV-"
                    + procesaXML.getMapDatos().get("first_name") + " "
                    + procesaXML.getMapDatos().get("last_name");// + ".odt";
            // OutputStream out = new FileOutputStream(new File(
            // "c://temp//DocxProject_Out.docx" ));
            File master = File.createTempFile("master", ".odt");
            OutputStream out = new FileOutputStream(master);
            report.process(context, out);

            InputStream inputConvert = new FileInputStream(master);
            master.deleteOnExit();
            InputStream inputFile = new BufferedInputStream(inputConvert);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            byte[] byteBuffer = new byte[4096];
            int byteBufferLength = 0;
            while ((byteBufferLength = inputFile.read(byteBuffer)) > 0) {
                bytes.write(byteBuffer, 0, byteBufferLength);
            }

            inputFile.close();
            OOoInputStream inputStream = new OOoInputStream(bytes.toByteArray());
            OOoOutputStream outputStream = new OOoOutputStream();
            converter.convert(inputStream, outputStream, "MS Word 97", null);

            nombreDocumento = "CV-"
                    + procesaXML.getMapDatos().get("first_name") + " "
                    + procesaXML.getMapDatos().get("last_name") + ".doc";

            FileOutputStream out1 = new FileOutputStream(rutaDocWord + ".doc");
            out1.write(outputStream.toByteArray());
            out1.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
